import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveUpdateAPIView, UpdateAPIView
from rest_framework.mixins import UpdateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from rest_framework.generics import ListAPIView

# from meiduo_mall.utils.captcha import captcha
from code_monkey.utils.captcha import captcha
# from code_monkey.utils.pagination import StandardResultsSetPagination
from complains.models import Complain
from complains.utils.pagination import StandardResultsSetPagination
from news.models import News
from quesanw.models import QuestionModel, AnswerModel, QuestionFocusModel, UserFocusTagModel, QuestionTagModel
from users import constants
from users import serializers
from users.models import User, UserInfo
# from verifications.serializers import ImageCodeCheckSerializer

from celery_tasks.sms import tasks as sms_tasks
# from .utils.captcha.captcha import captcha
# from users.serializers import ImageCodeCheckSerializer


# class ImageCodeView(APIView):
#     """# 图片验证码视图"""
#     def get(self,request,image_code_id):
#
#         # 生成验证码
#         text,image = captcha.captcha.generate_captcha()
#         print(text)
#         # 保存验证码
#         # 创建redis对象
#         redis_conn = get_redis_connection('verify_codes') #type:redis
#         redis_conn.setex('img%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
#         return  HttpResponse(image,content_type='image/jpg')


# 访问方式： GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
from users.serializers import UserDetailSerializer, MyQuestionSerializer, MyAnwserSerializer, UserSerializer, \
    MyfocusQuestion, QuestionTagModelSerializer, MyfocusTag, AddUserBrowsingHistorySerializer, NewsSerializer, \
    SetCityserializer, PersonalCountSerializer, PersonalCountChangeSerializer, FocusQestionSerilizer


class SmsCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：
        mobile, image_code_id, text
    """

    def get(self, request, mobile):
        """创建短信验证码"""
        # 判断验证码是否在６０秒内
        # serializers = self.get_serializer(data =request.query_params)
        # serializers.is_valid(raise_exception = True)
        count = User.objects.filter(mobile=mobile).count
        # if  count:
        #
        #
        #     return Response(data={'ermsg':'手机号已注册'},status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)

        # 保存短信验证码
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, constants.SMS_TMP)
        pl.execute()

        # 发送短信验证码

        sms_code_exmpirs = constants.SMS_CODE_REDIS_EXPIRES // 60
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,sms_code_exmpirs],constants.SMS_TMP)
        # sms_tasks.send_sms_code(mobile,sms_code,sms_code_exmpirs)

        return Response({'message': 'OK'})


# 请求方式： GET usernames/(?P<username>\w{5,20})/count/
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """
        用户名数量
        """

    def get(self, request, username):
        """
               获取指定用户名数量
            """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# 请求方式： GET mobiles/(?P<mobile>1[3-9]\d{9})/count
# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """获取电话号码数量"""

    def get(self, request, mobile):
        """查询电话号码的是数量"""
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'momile': mobile,
            'count': count
        }

        return Response(data)


class UserView(CreateAPIView):
    """用户注册视图"""
    """
        用户注册
        传入参数：
            username, password, password2, sms_code, mobile, allow
        """
    serializer_class = serializers.CreateUserSerializer


class PersonalCenter(RetrieveAPIView):
    """个人中心"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        user_id = self.request.user.id
        try:
            user_info = UserInfo.objects.get(user_id=user_id)
        except UserInfo.DoesNotExist:
            return None

        return user_info


class MyQuestion(ListAPIView):
    """我的 提问"""
    permission_classes = [IsAuthenticated]
    queryset = QuestionModel.objects.all().prefetch_related('author').order_by('update_time')

    pagination_class = StandardResultsSetPagination
    serializer_class = MyQuestionSerializer

    # def get_queryset(self):
    #     user_id = self.request.user.id
    #     user_info = QuestionModel.objects.filter(author=user_id).order_by('update_time')
    #     return user_info
    # def get_object(self):
    #     user = self.request.user
    #     return user


class MyAnwser(ListAPIView):
    """我的回答视图"""
    permission_classes = [IsAuthenticated]
    queryset = AnswerModel.objects.all().prefetch_related('author').order_by('update_time')
    serializer_class = MyAnwserSerializer
    pagination_class = StandardResultsSetPagination


class MyHistory(APIView):
    """我的浏览历史记录"""
    pass


class MyFocusQuestion(ListAPIView):
    """我关注的问题"""
    permission_classes = [IsAuthenticated]
    # queryset =QuestionFocusModel.objects.all().prefetch_related('question').order_by('question')
    queryset = QuestionFocusModel.objects.all()
    serializer_class = MyfocusQuestion
    pagination_class = StandardResultsSetPagination


class MyFocusTag(ListAPIView):
    """我关注的标签"""
    permission_classes = [IsAuthenticated]
    queryset = UserFocusTagModel.objects.all().prefetch_related('tag').order_by('tag')
    serializer_class = MyfocusTag
    pagination_class = StandardResultsSetPagination


class UserBrowsingHistoryView(CreateAPIView):
    """用户浏览历史记录"""
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取浏览历史记录"""

        username = request.user.username

        redis_conn = get_redis_connection('history')

        # 获取新闻的历史记录
        news_history = redis_conn.zrange("history_news_%s" % username, start=0,
                                         end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        news_history_id = []

        for history_ in news_history:
            history_ = int(history_.decode())

            history_i = QuestionModel.objects.get(id=history_)

            news_history_id.append(history_i)
        news_s = NewsSerializer(news_history_id, many=True)

        # 获取问答的浏览历史记录
        question_history = redis_conn.zrange("history_question_%s" % username, start=0,
                                             end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1, desc=False, )

        question_history_id = []

        for history_ in question_history:
            history_ = int(history_.decode())

            history_i = News.objects.get(id=history_)
            question_history_id.append(history_i)

        question_s = NewsSerializer(question_history_id, many=True)

        # 获取问答的浏览历史记录
        spit_history = redis_conn.zrange("history_spit_%s" % username, start=0,
                                         end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1, desc=False, )
        spit_history_id = []

        for history_ in spit_history:
            history_ = int(history_.decode())

            history_i = Complain.objects.get(id=history_)
            spit_history_id.append(history_)

        spit_s = NewsSerializer(spit_history_id, many=True)

        data = {
            "news": news_s.data,
            "question": question_s.data,
            "spit": spit_s.data,

        }
        return Response(data)


class SetCity(UpdateAPIView):
    """修改基本个人信息"""
    permission_classes = [IsAuthenticated]
    serializer_class = SetCityserializer

    def get_object(self):
        user = self.request.user

        return UserInfo.objects.filter(user_id=user).get()



class PersonalCount(RetrieveAPIView):
    """
    获取个人账户信息:UserInfo表里的信息
    """
    permission_classes = [IsAuthenticated]
    serializer_class = PersonalCountSerializer

    def get_object(self):

        user_id = self.request.user.id
        try:
            user_info = UserInfo.objects.get(user_id=user_id)
        except UserInfo.DoesNotExist:
            return None

        return user_info

class PersonalCountChange(UpdateAPIView):
    """
    修改个人账户信息:User表里的信息
    """
    permission_classes = [IsAuthenticated]
    serializer_class = PersonalCountChangeSerializer

    def get_object(self):
        print(self.request.user.id)
        user_id = self.request.user.id
        try:
            user_info = User.objects.get(id=user_id)
        except UserInfo.DoesNotExist:
            return None
        else:
            return user_info

class FocusQestion(UpdateAPIView):
    """我的问题关注"""
    permission_classes = [IsAuthenticated]
    serializer_class = FocusQestionSerilizer

    def get_object(self):
        user=self.request.user.id
        return User.objects.get(id=user)